package logic

import (
	"cart/cache"
	"cart/mysql"
	"context"

	"cart/cart"
	"cart/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *cart.CartAddRequest) (*cart.CartAddResponse, error) {
	// todo: 购物车添加

	var err error
	var g mysql.Goods
	err = g.Finds(int(in.GoodsId))
	if err != nil {
		logx.Error("商品已存在购物车中", err)
		return nil, err
	}
	//查询库存是否充足
	if g.Stock < int(in.GoodsNum) {
		logx.Error("库存不足", err)
		return nil, err
	}

	if cache.CartExist(int(in.UserId), int(in.GoodsId)) {

	} else {

		cartMap := map[string]interface{}{
			"goods_id":    in.GoodsId,
			"goods_name":  g.Name,
			"goods_num":   g.Stock,
			"goods_price": g.Price,
			"user_id":     in.UserId,
		}

		if cache.CartAdd(int(in.UserId), int(in.GoodsId), cartMap) != nil {
			logx.Error("购物车添加失败", err)
			return nil, err
		}
	}

	return &cart.CartAddResponse{}, nil
}
